from flask import current_app, Blueprint, request
from flask_json import as_json
from flask_jwt_extended import jwt_required

from app import db
from app.admin.is_staff_user import is_staff_user
from app.auth.auth_decorator import has_role
from app.models import CommonResult, AuthPermission, AuthRolePermission, AuthUserPermission, CommonPage
from app.common.enums import AuthPermissionType, RoleCodeEnum
from app.form.auth_permission_form import AuthPermissionForm

log = current_app.logger
admin_permission = Blueprint('admin_permission', __name__, url_prefix='/admin/permission')


# 注册蓝图
def register_controller(app):
    app.register_blueprint(admin_permission)


# 分页查询
@admin_permission.post('/page')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def page():
    data = request.get_json()
    current = 1
    page_size = 10
    page_obj = AuthPermission.query
    if data:
        current = data.get('current') or 1
        page_size = data.get('page_size') or 10
        p_code = data.get('p_code')
        p_name = data.get('p_name')
        is_enabled = data.get('is_enabled')
        if p_code and p_code.strip():
            page_obj = page_obj.filter(AuthPermission.p_code == p_code)
        if p_name and p_name.strip():
            page_obj = page_obj.filter(AuthPermission.p_name.like('%{keyword}%'.format(keyword=p_name)))
        if is_enabled is not None:
            page_obj = page_obj.filter(AuthPermission.is_enabled == is_enabled)

    # 分页查询
    page_data = page_obj.paginate(
        page=current,
        per_page=page_size,
        error_out=False
    )
    return CommonResult(data=CommonPage(page_data))


# 列表查询
@admin_permission.post('/list')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def admin_permission_list():
    data = request.get_json()
    query = AuthPermission.query
    if data:
        if data.get("p_type") is not None:
            p_type = AuthPermissionType._value2member_map_.get(data.get("p_type"))
            query = query.filter(AuthPermission.p_type == p_type)
        if data.get("is_enabled") is not None:
            query = query.filter(AuthPermission.is_enabled == data.get("is_enabled"))
    data_list = query.all()
    return CommonResult(data=data_list)


# 获取详情
@admin_permission.get('/get/<int:permission_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def info(permission_id):
    record_info = AuthPermission.query.get(permission_id)
    if record_info is None:
        return CommonResult(code=500, msg='记录不存在')
    return CommonResult(data=record_info, msg='获取成功')


# 添加记录
@admin_permission.post('/add')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def add():
    AuthPermissionForm().api_validate()
    data = request.get_json()
    # 填充数据
    record = AuthPermission()
    record.__dict__.update(data)
    # 保存数据库
    db.session.add(record)
    db.session.commit()
    return CommonResult(data=data, msg='保存成功')


@admin_permission.post('/update')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def update():
    AuthPermissionForm().api_validate()
    data = request.get_json()
    if data and data.get('id') is not None:
        record = AuthPermission.query.get(data.get('id'))
        if record is None:
            return CommonResult(code=500, msg='修改记录不存在')
        db.session.query(AuthPermission).filter(AuthPermission.id == data.get('id')).update(data)
        db.session.commit()
        return CommonResult(data=data, msg='修改成功')
    return CommonResult(code=500, msg='请传入修改记录的ID')


# 删除记录
@admin_permission.get('/delete/<int:permission_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def delete(permission_id):
    # 查询是否存在
    record = AuthPermission.query.get(permission_id)
    if record is None:
        return CommonResult(code=500, msg='删除的记录不存在')
    # 删除主记录和关联记录
    db.session.query(AuthRolePermission).filter(AuthRolePermission.permission_id == permission_id).delete()
    db.session.query(AuthUserPermission).filter(AuthUserPermission.permission_id == permission_id).delete()
    db.session.delete(record)
    db.session.commit()
    return CommonResult(msg='删除成功')
